var express = require('express');
var router = express.Router();
var xml2js = require('xml2js');
var builder = new xml2js.Builder(); // JSON->xml
var parser = new xml2js.Parser({
    explicitArray: false,
    ignoreAttrs: true
}); //xml -> json
var User = require('../models/User'); // 引入模型
var Spread = require('../models/Spread'); // 引入模型
var wxpay = require('../common/pay');
var Found = function (appid) {
    console.log(appid);
    var promise = new Promise((resolve, reject) => {})
    return promise;
}
var get_client_ip = function (req) {
    var promise = new Promise((resolve, reject) => {
        var ip = req.headers['x-forwarded-for'] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress || '';
        if (ip.split(',').length > 0) {
            ip = ip.split(',')[0]
        }
        return resolve(ip)
    });
    return promise;
};

/* GET users listing. */
var app = express();
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization,Origin,Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('X-Powered-By', ' 3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});
router.all('/', function (req, res) {
    res.send({
        title: 'asihdsuai',
        content: '欢迎访问Express'
    })
})
router.post('/login', function (req, res) {
    //获取查询参数
    console.log('用户星系')
    let openid = req.body.openid;
    let datas = req.body;
    console.log("dtata:", req.body)
    User.find({
        openid: openid
    }, (err, data) => {
        if (err) return false;
        if (data.length > 0) {
            res.send({
                msg: '用户已存在',
                data: [],
                status: 3
            })
        } else {
            User.create(datas, (err) => {
                if (err) return false;
                Spread.find({
                    city: datas.city
                }, (err, data) => {
                    if (err) return res.send({
                        msg: '请求失败'
                    });
                    if (data.length > 0) {
                        Sprend.where({
                            city: datas.city
                        }).update({
                            $inc: {
                                count: 1
                            }
                        }, (err, data) => {
                            if (err) return res.send({
                                msg: '更新出错'
                            });
                           
                        })
                    }else{
                        Sprend.create({city:datas.city,count:1},(err,data)=>{
                            if(err) res.send({msg:'插入失败'});
                            res.send({
                                msg: '添加用户成功',
                                data: [],
                                status: 4
                            })
                        })
                    }
                })
            })
        }
    })
});
router.post('/getUserInfo', (req, res) => {
    let datas = req.body;
    User.findOne(datas, (err, data) => {
        if (err) return false;
        res.send({
            msg: '获取用户信息成功',
            data: data,
            status: 4
        })
    })

})
router.post('/adduser', function (req, res) {
    //获取查询参数
    //console.log(req.query);
    console.log(req.body.username);
    var name = req.body.username;
    var user = req.body;
    //console.log(User);
    if (!req.body.username) return res.send({
        msg: '用户名不能为空',
        data: 3,
    });
    User.find({
        'username': name
    }, (err, data) => {
        if (err) return console.log('查询失败');
        if (data.length > 0) return res.send({
            msg: "添加的用户已存在",
            code: 3,
            data: []
        });

        User.create(user, (err) => {
            if (err) return console.log("插入数据出错" + err);
            User.find({
                    'username': name
                }, (err, rul) => {
                    if (err) return console.log("查询数据数据出错" + err);
                    console.log(rul);
                    res.send({
                        msg: '添加用户成功',
                        code: 4,
                        data: {
                            name: rul,
                            psaaword: 'roots'
                        }
                    })
                }

            )

        })


    })
});
router.post('/userlist', function (req, res) {
    User.find({}, (err, data) => {
        if (err) return console.log('查询失败');
        if (data.length > 0) {
            res.send({
                msg: "查询成功",
                status: 3,
                data: data
            })
        } else {
            res.send({
                msg: '管理员不存在',
                status: 4,
                data: []
            })
        }
    })
});

router.post("/openid", async (req, res) => {
    const Ut = require("../common/api");
    try {
        //console.log(req.body);
        let appId = req.body.appId;
        let js_code = req.body.code;
        let nickName = req.body.nickName;
        let avatarUrl = req.body.avatarUrl;
        let gender = req.body.gender;
        let country = req.body.country;
        let city = req.body.city;
        let province = req.body.province;
        var type = req.body.type;
        var a = new Date();
        var yy = a.getFullYear();
        var mm = (a.getMonth() + 1) > 9 ? (a.getMonth() + 1) : '0' + (a.getMonth() + 1);
        var dd = a.getDate() > 9 ? a.getDate() : '0' + a.getDate();
        var hh = a.getHours() > 9 ? a.getHours() : '0' + a.getHours();
        var min = a.getMinutes() > 9 ? a.getMinutes() : '0' + a.getMinutes();
        var sec = a.getSeconds() > 9 ? a.getSeconds() : '0' + a.getSeconds();
        var time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + sec;
        //console.log('code',req.body.code)
        let secret = await Found(appId);
        console.log(secret);
        let opts = {
            url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&grant_type=authorization_code&js_code=${js_code}`
        }
        console.log(opts);
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        //https://api.weixin.qq.com/sns/oauth2/access_token?
        //https://api.weixin.qq.com/sns/jscode2session?
        let r1 = await Ut.promiseReq(opts);
        r1 = JSON.parse(r1);
        //console.log(r1);
        var openid = r1.openid;
        var Rdb = {
            appId: appId,
            openId: openid,
            nickName: nickName,
            avatarUrl: avatarUrl,
            city: city,
            province: province,
            country: country,
            gender: gender,
            date: time,
            type: type,
            isPay: false,
        }

        // console.log('openid',openid)
        res.send({
            data: r1,
            status: 3,
            msg: '获取用户信息成功'
        });
    } catch (e) {
        console.log(e);
        res.send({
            data: {},
            status: 3,
            msg: '获取用户信息失败'
        });
    }
});

router.post('/payment', function (req, res, next) {

    //var ip=await get_client_ip(req);
    var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
    //console.log('real_ip',real_ip);
    //console.log('ip',ip); 
    var attach = "1276687601";
    var body = "微信好友恢复教程";
    var mch_id = "1513737961"; //商户ID 
    var openid = req.body.openId;
    var appId = req.body.appId ? req.body.appId : 'wxdc3db9890d05d548';
    var timestamp = (new Date()).getTime();
    var bookingNo = timestamp + '' + parseInt(Math.random() * 1000000000000); //订单号 
    //console.log('bookingNo',bookingNo);
    var total_fee = 400;
    var notify_url = "https://www.yteris.com/v1/users/wxpay"; //通知地址 
    //var notify_url = "http://localhost:8089/users/wxpay"; //通知地址
    wxpay.order(appId, attach, body, mch_id, openid, bookingNo, total_fee, notify_url, real_ip).then(function (data) {
        var pay = data;
        //console.log('pay',pay);
        res.send({
            status: 3,
            data: pay,
            msg: '支付参数请求成功'
        });
    });
});


router.post('/shoppayment', function (req, res, next) {
    console.log(req.body.money);
    //var ip=await get_client_ip(req);
    var real_ip = req.get("X-Real-IP") || req.get("X-Forwarded-For") || req.ip;
    //console.log('real_ip',real_ip);
    //console.log('ip',ip); 
    var attach = "1276687602";
    var body = "青爱水果商城";
    var mch_id = "1513737961"; //商户ID 
    var openid = req.body.openId;
    var appId = req.body.appId;
    var timestamp = (new Date()).getTime();
    var bookingNo = timestamp + '' + parseInt(Math.random() * 1000000000000); //订单号 
    //console.log('bookingNo',bookingNo);
    var total_fee = req.body.money * 100;

    var notify_url = "https://www.yteris.com/v1/users/wxpays"; //通知地址 
    //var notify_url = "http://localhost:8089/users/wxpay"; //通知地址
    wxpay.order(appId, attach, body, mch_id, openid, bookingNo, total_fee, notify_url, real_ip).then(function (data) {
        var pay = data;
        //console.log('pay',pay);
        res.send({
            status: 3,
            data: pay,
            msg: '支付参数请求成功'
        });
    });
});
router.all('/wxpay', function (req, res) {
    var body = req.rawBody || req.body;
    console.log('payment', '支付中....');
    console.log(body);
    parser.parseString(body, function (err, data) {
        console.log('data', '没结果');
        console.log(data);
        if (data.xml) {
            var data = data.xml;
            console.log(data);
            Role.update({
                openId: data.openid
            }, {
                isPay: true
            }, (err, data) => {
                if (err) return console.log('查询失败');
                console.log('payment', '支付成功');
            })
        }
    })

});

router.all('/wxpays', function (req, res) {
    var body = req.rawBody || req.body;
    console.log('payment', '支付中....');
    console.log(body);
    parser.parseString(body, function (err, data) {
        console.log('data', '没结果');
        console.log(data);
        if (data.xml) {
            var data = data.xml;
            console.log('payment', '支付成功');
            //  Role.update({openId:data.openid},{isPay:true},(err,data)=>{
            //      if(err) return console.log('查询失败');
            //      console.log('payment','支付成功');
            //  })
        }
    })

});
router.post('/findUser', function (req, res) {
    var pageSize = req.body.pageSize;
    var pageNo = req.body.pageNo;


});
router.post('/findTodayUser', function (req, res) {
    var date = new Date();
    var yy = date.getFullYear();
    var mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
    var dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var dates = yy + '-' + mm + '-' + dd;
    var qs = new RegExp(dates);
    console.log(qs);

});
router.post('/findTodayUserPay', function (req, res) {
    var date = new Date();
    var yy = date.getFullYear();
    var mm = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
    var dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var dates = yy + '-' + mm + '-' + dd;
    var qs = new RegExp(dates);

});
router.post('/findTotalUser', function (req, res) {

});
router.post('/addmpa', function (req, res) {
    console.log(req.body);
    var dbs = req.body;


});
router.post('/userremove', function (req, res) {
    var id = req.body.id;
    User.remove({
        _id: id
    }, (err, data) => {
        if (err) return console.log('查询失败');
        res.send({
            msg: "删除成功",
            status: 3,
            data: {}
        })

    })
})

module.exports = router;